#pragma once

#include <pthread.h>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "LockGuard.hpp"
#include "Thread.hpp"

using namespace ThreadModule;

const static int gdefaultthreadnum = 5;

template <typename T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadWakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    // 单例模式，构造函数私有
    ThreadPool(int threadnum = gdefaultthreadnum)
        : _threadnum(threadnum)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        LOG(INFO, "ThreadPool Construct()\n");
    }
    void InitThreadPool()
    {
        // 将this绑定为HandlerTask的第一个参数，placeholders替换为Thread内部调用_func(类型为<void(std::string)>)时的参数string
        std::function<void(std::string)> func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1);

        for (int i = 0; i < _threadnum; i++)
        {
            std::string name = "thread-" + std::to_string(i + 1);
            // func和name作为创建Thread的参数
            _threads.emplace_back(func, name);
            LOG(INFO, "init thread %s done\n", name.c_str());
        }
        _isrunning = true;
    }
    void Start()
    {
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }

    // 类成员函数，形参带有this指针
    void HandlerTask(std::string name)
    {
        LOG(INFO, "%s is running...\n", name.c_str());
        while (true)
        {
            // 1.保证队列安全
            LockQueue();
            // 2. 队列中没有任务，进入等待
            while (_task_queue.empty() && _isrunning)
            {
                _waitnum++;
                ThreadSleep();
                _waitnum--;
            }
            // 2.1如果进程池退出&&任务队列为空
            if (_task_queue.empty() && !_isrunning)
            {
                UnlockQueue();
                break;
            }
            // 2.2 线程池退出也要处理完任务
            // 3.处理任务
            T t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();
            LOG(DEBUG, "%s get a task\n", name.c_str());
            // 4.每个线程独立处理任务
            t();
            LOG(DEBUG, "%s handler a task\n", name.c_str());
        }
    }
    // 禁用拷贝和赋值重载
    ThreadPool(const ThreadPool<T> &) = delete;
    ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetInstance()
    {
        // 如果是多线程获取线程池对象下面的代码就有问题了！！
        // 只有第一次会创建对象，后续都是获取
        // 保证第二次之后，所有线程，不用在加锁，直接返回_instance单例对象
        if (nullptr == _instance)
        {
            LockGuard lockguard(&_lock);
            // 双判断的方式，可以有效减少获取单例的加锁成本，而且保证线程安全
            if (nullptr == _instance)
            {
                _instance = new ThreadPool<T>();
                _instance->InitThreadPool();
                _instance->Start();
                LOG(DEBUG, "创建线程池单例\n");
                return _instance;
            }
        }
        LOG(DEBUG, "获取线程池单例\n");
        return _instance;
    }
    void Stop()
    {
        LockQueue();
        _isrunning = false;
        ThreadWakeupAll();
        UnlockQueue();
    }
    void Wait()
    {
        for (auto &thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quit...\n", thread.name().c_str());
        }
    }
    bool Enqueue(const T &t)
    {
        bool ret = false;
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(t);
            if (_waitnum > 0)
                ThreadWakeup();
            LOG(DEBUG, "enqueue task success\n");
            ret = true;
        }
        UnlockQueue();
        return ret;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadnum;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    int _waitnum;
    bool _isrunning;

    // 添加单例模式
    static ThreadPool<T> *_instance;
    static pthread_mutex_t _lock;
};

template <typename T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;